package logic

import (
	"context"
	"net/http"
	"srv/srv"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ALiPayLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewALiPayLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ALiPayLogic {
	return &ALiPayLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ALiPayLogic) ALiPay(w http.ResponseWriter, r *http.Request) (resp *types.ALiPayResponse, err error) {
	// todo: add your logic here and delete this line
	outTradeNo := r.FormValue("out_trade_no")
	tradeStatus := r.FormValue("trade_status")
	//枚举名称	枚举说明
	//WAIT_BUYER_PAY	交易创建，等待买家付款。
	//TRADE_CLOSED	未付款交易超时关闭，或支付完成后全额退款。
	//TRADE_SUCCESS	交易支付成功。
	//TRADE_FINISHED	交易结束，不可退款。
	var status int
	if tradeStatus == "TRADE_SUCCESS" {
		status = 2
	} else if tradeStatus == "TRADE_FINISHED" {
		status = 3
	} else if tradeStatus == "WAIT_BUYER_PAY" {
		status = 4
	} else {
		return
	}
	_, err = l.svcCtx.Srv.UpdateOrder(l.ctx, &srv.UpdateOrderRequest{
		OrderSn:     outTradeNo,
		OrderStatus: int64(status),
	})
	if err != nil {
		return nil, err
	}
	w.Write([]byte("success"))
	return
}
